package com.jie.component.threadpool.factory;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicLong;

/**
 * @author jie
 * @version 1.0 2025-02-13
 */
public abstract class AbstractNameThreadFactory implements ThreadFactory {

    protected static final AtomicLong POOL_NUM = new AtomicLong(1);
    private final ThreadGroup group;
    private final AtomicLong threadNum = new AtomicLong(1);
    private String namePrefix = "";

    public AbstractNameThreadFactory() {
        SecurityManager s = System.getSecurityManager();
        group = (s != null) ? s.getThreadGroup() : Thread.currentThread().getThreadGroup();
        namePrefix = getNamePrefix() + "--thread--";
    }

    public abstract String getNamePrefix();

    @Override
    public Thread newThread(Runnable r) {
        String name = namePrefix + threadNum.getAndIncrement();
        Thread t = new Thread(group, r, name, 0);
        // 守护线程
        if (t.isDaemon()) {
            t.setDaemon(false);
        }
        if (t.getPriority() != Thread.NORM_PRIORITY) {
            t.setPriority(Thread.NORM_PRIORITY);
        }
        return t;
    }
}
